package com.yyj1205.jsongenrator.controller;

import com.yyj1205.jsongenrator.entity.Result;
import com.yyj1205.jsongenrator.service.ErnieBotService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @Title: JsonGeneratorController
 * @Author yyj1205
 * @Package com.yyj1205.jsongenrator.controller
 * @Date 2024-09-22 21:10
 * @description: 生成json的控制器
 */
@Slf4j
@RestController
@RequestMapping("/JsonGenerator")
@ApiModel("Json生成")
public class JsonGeneratorController {

    @Autowired
    private ErnieBotService ernieBotService;

    @GetMapping("/getSession")
    @ApiOperation("申请SessionId，此id用于保存上下文，请在cookie中缓存该id")
    @ResponseBody
    public Result<String> getSession(@RequestParam("userName") String userName) throws IOException {
        String session = ernieBotService.getSession(userName);
        if(session == null){return Result.fail("缓存申请失败");}
        return Result.success(session);
    }

    @GetMapping("/postMessage")
    @ApiOperation("向会话发送数据")
    @ResponseBody
    public Result<String> postMessage(@RequestParam("message") String message,
                                      @RequestParam("sessionId") String sessionId){
        try {
            String result = ernieBotService.postMessage(sessionId, message);
            return Result.success(result);
        }
         catch (Exception e){
            return Result.fail(e.getMessage());
         }
    }

    @GetMapping("/deleteSession")
    @ApiOperation("手动删除Session中的数据，数据有定期清理，也可调用此接口主动清理数据")
    @ResponseBody
    public Result<String> deleteSession(@RequestParam("sessionId") String sessionId){
        ernieBotService.deleteSession(sessionId);
        return Result.success(sessionId);
    }

    @GetMapping("/loadMessage")
    @ApiOperation("基于对话的数据生成json并填装至指定路径")
    @ResponseBody
    public Result<String> loadMessage(@RequestParam("sessionId") String sessionId){
        try {
            ernieBotService.loadMessage(sessionId);
        }
        catch (Exception e){
            return Result.fail(e.getMessage());
        }
        return Result.success(sessionId);
    }
}
